import { NavigationGuard } from 'vue-router/types/router'
import { getCurrentInstance, isVue2 } from 'vue-demi'

export function onBeforeRouteLeave(leaveGuard: NavigationGuard) {
  if (!isVue2) {
    return new Error('该hook只能在vue2环境使用') as any
  }
  const { options } = getCurrentInstance()?.proxy?.constructor as any
  const hooks: any = options.beforeRouteLeave || []
  hooks.push(leaveGuard)
  options.beforeRouteLeave = hooks
}

export function onBeforeRouteUpdate(updateGuard: NavigationGuard) {
  if (!isVue2) {
    return new Error('该hook只能在vue2环境使用') as any
  }
  const { options } = getCurrentInstance()?.proxy?.constructor as any

  const hooks: any = options.beforeRouteUpdate || []
  hooks.push(updateGuard)
  options.beforeRouteUpdate = hooks
}
